<?php

namespace IDock\Insurance\ZMBX\Response;

use IDock\Http\Request;
use IDock\Http\Response;

class AllZMBXResponse extends Response
{
    protected $records = [];

    protected $result = [];

    public function resolve(): Response
    {
        $body = $this->getBody();
        $body = json_decode($body, true);
        if ($this->printer) {
            $this->printer = new $this->printer;
        }
        if(empty($body)){
            return $this;
        }
        $responseCode = $body['head']['errorCode'] ?? '0';

        $errorMsg = $body['head']['returnMessage'] ?? '';
        if ($responseCode != '' && $responseCode != '0000') {
            $this->setError($errorMsg);
            return $this;
        }
        $this->setBody($body);
        return $this;
    }

    public function decrypt($secret,Request $request)
    {
        $data = str_replace(['', "\r\n", "\r", "\n"], ['', '', '', ''], $this->getBody());
        if(ctype_xdigit($data)){
            $body = openssl_decrypt(hex2bin($data), 'AES-128-ECB', $secret, OPENSSL_RAW_DATA);
            $request->decryptLogs($request->getRequestId(),$body);
            if(empty($body)){
                $this->setError('解密失败');
            }
            $this->setBody($body);
            return $this;
        }
        $this->setError('解密失败');
        return $this;
    }

    public function getRecords(string $string = '', $default = '')
    {
        if (strlen($string)) {
            return $this->records[$string] ?? $default;
        }
        return $this->records;
    }

    public function getResult(string $string, $default = '')
    {
        if (strlen($string)) {
            return $this->result[$string] ?? $default;
        }
        return $this->result;
    }
}
